package com.fone.player.activity.local;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.local.adapter.LocalMediaAdatper;
import com.fone.player.entity.MediaFile;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerFrom;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;

public class LocalMediaFragment extends Fragment implements OnClickListener {
	private String TAG = "LocalMediaFragment";
	private List<MediaFile> mVideos;
	private List<Boolean> mCheckBoxs;
	private View mView;
	private ListView lv_local_videos;

	private Button btn_local_more_video;

	private LinearLayout ll_local_delete;

	private Button btn_local_select_all;

	private Button btn_local_delete;
	private boolean hasSelectedAll;
	private LocalMediaAdatper mListVideoAdapter;

	private Handler mHandler;

	public void setHandler(Handler mHandler) {

		this.mHandler = mHandler;
	}

	public LocalMediaFragment() {

		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = LayoutInflater.from(getActivity()).inflate(
				R.layout.personal_local_file_view, null);
		initView();
		return mView;
	}

	public List<MediaFile> getVideos() {
		return mVideos;
	}

	public void setVideos(List<MediaFile> mVideos) {

		this.mVideos = mVideos;
	}

	public void setDeleted(boolean isDeleted) {
		if (mCheckBoxs != null && mCheckBoxs.size() > 0) {
			mCheckBoxs.set(0, isDeleted);
			notifyData();
			if (isDeleted) {// 删除模式
				btn_local_more_video.setVisibility(View.GONE);
				ll_local_delete.setVisibility(View.VISIBLE);
			} else {// 正常模式
				hasSelectedAll = false;
				btn_local_more_video.setVisibility(View.VISIBLE);
				ll_local_delete.setVisibility(View.GONE);
				for (int i = 0; i < mVideos.size(); i++) {
					mVideos.get(i).setDeleteSelected(false);
				}
				btn_local_select_all.setText("全选");
				btn_local_delete.setText("删除");
				btn_local_delete.setTextColor((getResources()
						.getColor(R.color.btn_unpress_text_color)));
			}
		}
	}

	public boolean getDeleted() {
		if (mCheckBoxs != null && mCheckBoxs.size() > 0) {
			return mCheckBoxs.get(0);
		} else {
			return false;
		}
	}

	private void initView() {
		mCheckBoxs = new ArrayList<Boolean>();
		mCheckBoxs.add(false);
		ll_local_delete = (LinearLayout) mView
				.findViewById(R.id.ll_local_delete);

		VideosItemClickListener listener = new VideosItemClickListener(mVideos);
		lv_local_videos = (ListView) mView.findViewById(R.id.lv_local_videos);
		lv_local_videos.setOnItemClickListener(listener);

		btn_local_more_video = (Button) mView
				.findViewById(R.id.btn_local_more_video);
		btn_local_select_all = (Button) mView
				.findViewById(R.id.btn_local_select_all);
		btn_local_delete = (Button) mView.findViewById(R.id.btn_local_delete);
		btn_local_more_video.setOnClickListener(this);
		btn_local_select_all.setOnClickListener(this);
		btn_local_delete.setOnClickListener(this);
		mListVideoAdapter = new LocalMediaAdatper(getActivity(), mVideos,
				mCheckBoxs, lv_local_videos, mHandler);
		lv_local_videos.setAdapter(mListVideoAdapter);
		// getLocalMedia(LocalActivity.MSG_GET_MEDIA);
	}

	// 获取本地视频
	private void getLocalMedia(int MediaType) {

		if (mHandler == null) {
			L.i(TAG, "getLocalMedia", "mHandler=" + mHandler);
			return;
		}
		Message message = mHandler.obtainMessage();
		message.what = MediaType;
		mHandler.sendMessage(message);
	}

	public void notifyData() {
		if (mListVideoAdapter != null) {
			mListVideoAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_local_select_all:
			hasSelectedAll = !hasSelectedAll;
			L.i(TAG, "hasSelectedAll:" + hasSelectedAll);
			for (int i = 0; i < mVideos.size(); i++) {
				if (!hasSelectedAll) {// 处于未全选状态
					L.i(TAG, "全部未选中！");
					mVideos.get(i).setDeleteSelected(false);

					btn_local_delete.setTextColor(getResources().getColor(
							R.color.btn_unpress_text_color));
					btn_local_delete.setText("删除");
					btn_local_select_all.setText("全选");
				} else {// 处于全选状态
					L.i(TAG, "全部选中！");
					btn_local_delete.setTextColor(getResources().getColor(
							R.color.btn_pressed_text_color));
					mVideos.get(i).setDeleteSelected(true);
					btn_local_delete.setText("删除(" + mVideos.size() + ")");
					btn_local_select_all.setText("取消全选");
				}
			}

			mListVideoAdapter.notifyDataSetChanged();
			break;

		case R.id.btn_local_delete:
			int count = 0;
			for (int i = 0; i < mVideos.size(); i++) {
				if (mVideos.get(i).isDeleteSelected()) {
					count++;
				}
			}
			if (count <= 0) {
				Toast.makeText(getActivity(), "没有选中的视频", Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				// 判断存储设备是否挂载
				if (!SystemUtil.getInstance().isStorageMounted()) {
					FoneUtil.showToast(getActivity(),
							R.string.no_sdcard_mounted_text);
					return;
				}

				for (int i = mVideos.size(); i > 0; i--) {
					if (mVideos.get(i - 1).isDeleteSelected()) {
						String path = mVideos.get(i - 1).getMediaFilePath();
						int result = StorageModule.getInstance()
								.deleteFileByFilePath(path);
						L.i(TAG, "result:" + result);
					}
				}
				// 如果全部删除了
				if (mVideos.size() == count) {
					setDeleted(false);
				}
				btn_local_select_all.setText("全选");
				mHandler.sendEmptyMessage(LocalActivity.MSG_GET_MEDIA);
				mHandler.sendEmptyMessage(LocalActivity.MSG_GET_MEDIA_FOLDER);
			}

			// });

			mListVideoAdapter.notifyDataSetChanged();
			Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
			btn_local_delete.setText("删除");
			btn_local_delete.setTextColor(getResources().getColor(
					R.color.btn_unpress_text_color));
			break;
		case R.id.btn_local_more_video:
			getLocalMedia(LocalActivity.MSG_GET_ALL_MEDIA);
			break;
		default:
			break;
		}
	}

	private class VideosItemClickListener implements OnItemClickListener {
		private List<MediaFile> list;

		public VideosItemClickListener(List<MediaFile> list) {
			this.list = list;
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			CheckBox mBox = (CheckBox) view
					.findViewById(R.id.cb_local_selected);
			if (ll_local_delete.getVisibility() == View.VISIBLE) {

				list.get(position).setDeleteSelected(
						!list.get(position).isDeleteSelected());
				mBox.setChecked(list.get(position).isDeleteSelected());
				int count = 0;
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).isDeleteSelected()) {
						count++;
					}
				}
				if (count > 0) {
					if (count == mVideos.size()) {
						hasSelectedAll = true;
						btn_local_select_all.setText("取消全选");
					} else {
						hasSelectedAll = false;
						btn_local_select_all.setText("全选");
					}
					btn_local_delete.setText("删除(" + count + ")");
					btn_local_delete.setTextColor(getResources().getColor(
							R.color.btn_pressed_text_color));
				} else {
					hasSelectedAll = false;
					btn_local_select_all.setText("全选");
					btn_local_delete.setText("删除");
					btn_local_delete.setTextColor(getResources().getColor(
							R.color.btn_unpress_text_color));
				}
			} else if (ll_local_delete.getVisibility() == View.GONE) {

				// 判断存储设备是否挂载
				if (!SystemUtil.getInstance().isStorageMounted()) {
					FoneUtil.showToast(getActivity(),
							R.string.no_sdcard_mounted_text);
					return;
				}
				
				// 将该集合的所有url传入播放器
				String[] MediaPath = new String[mVideos.size()];
				for (int i = 0; i < mVideos.size(); i++) {
					MediaPath[i] = mVideos.get(i).getMediaFilePath();
					L.i(TAG, "mediaPath:" + mVideos.get(i).getMediaFilePath());
				}
				Intent intent = new Intent(getActivity(),
						FonePlayerActivity.class);
				intent.putExtra("from", PlayerFrom.LOCAL_INTERNAL);
				intent.putExtra("index", position);
				intent.putExtra("urls", MediaPath);
				getActivity().startActivity(intent);

			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		L.i(TAG, "onResume", "mVideos=" + mVideos);
		if (mVideos == null || mVideos.size() == 0) {

			getLocalMedia(LocalActivity.MSG_GET_MEDIA);
		} else {
			L.i(TAG, "onResume", "mVideos size:" + mVideos.size());
			mListVideoAdapter.notifyDataSetChanged();
		}
	}
}
